package com.ciwong.epaper.modules.epaper.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.adapter.HotWordAdapter;
import com.ciwong.epaper.modules.epaper.adapter.SearchBookAdapter;
import com.ciwong.epaper.modules.epaper.bean.BookCaseBean;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.SearchBookKeyNameBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.EpaperRequest;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.bean.SchoolDetail;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by albus on 2017/4/6.
 */

public class SearchBookActivity extends BaseActivity implements PullToRefreshView.OnHeaderRefreshListener,
        View.OnClickListener,
        PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemClickListener {
    /**
     * 每页数据大小
     */
    private static final int LOAD_PAGE_SIZE = 30;

    /**
     * 搜索结果显示
     */
    private ListView lv_searchResult;
    /**
     * 正在搜索中的页面
     */
    private RelativeLayout rel_searching;

    /**
     * 搜索结果为空
     */
    private RelativeLayout rel_search_empty;

    /**
     * 搜索关键字
     */
    private EditText edt_searching_book_str;
    /**
     * 搜索中的动画图片
     */
    ImageView iv_searching_book;
    /**
     * 加载更多
     */
    PullToRefreshView plv_searchbook;
    ImageView iv_search_dot1;
    ImageView iv_search_dot2;
    ImageView iv_search_dot3;
    /**
     * 热门搜索词语
     */
    private ListView lv_hot_word;
    private LinearLayout ll_hot_word;
    private HotWordAdapter hotWordAdapter;
    private List<SearchBookKeyNameBean> searchBookKeyNameBeanList = new ArrayList<SearchBookKeyNameBean>();

    private SearchBookAdapter searchBookadapter;
    private List<EpaperInfo> searchBookList = new ArrayList<EpaperInfo>();


    @Override
    protected int setView() {
        return R.layout.activity_searchbook;

    }

    /**
     * 清除搜索关键字
     */
    ImageView iv_clear_keywords;

    @Override
    protected void findViews() {
//        View headerView = LayoutInflater.from(this).inflate(R.layout.searching_header_view, null, false);

        plv_searchbook = (PullToRefreshView) findViewById(R.id.plv_searchbook);
        lv_searchResult = (ListView) findViewById(R.id.lv_searchbook);
//        lv_searchResult.addHeaderView(headerView);
        rel_searching = (RelativeLayout) findViewById(R.id.rel_searching);
        rel_search_empty = (RelativeLayout) findViewById(R.id.rel_search_empty);
        iv_searching_book = (ImageView) findViewById(R.id.iv_searching_book);
        edt_searching_book_str = (EditText) findViewById(R.id.edt_searching_book_str);
        edt_searching_book_str.setSingleLine();
        ll_hot_word = (LinearLayout) findViewById(R.id.ll_hot_word);
        lv_hot_word = (ListView) findViewById(R.id.lv_hot_word);
        iv_search_dot1 = (ImageView) findViewById(R.id.iv_search_dot1);
        iv_search_dot2 = (ImageView) findViewById(R.id.iv_search_dot2);
        iv_search_dot3 = (ImageView) findViewById(R.id.iv_search_dot3);
        iv_clear_keywords = (ImageView) findViewById(R.id.iv_clear_keywords);

    }

    @Override
    protected void initEvent() {

        plv_searchbook.setOnHeaderRefreshListener(this);
        iv_clear_keywords.setOnClickListener(this);
        plv_searchbook.setOnFooterRefreshListener(this);
        lv_searchResult.setOnItemClickListener(this);
        lv_hot_word.setOnItemClickListener(this);

//        setRightBtnListener(new ViewOnClickListener() {
//            @Override
//            public void avertRepeatOnClick(View view) {
//                MeJumpManager.jumpServices(R.string.go_back, SearchBookActivity.this, REQ_CODE_JUMP_TO_SERVICE_LIST);
//            }
//        });
        overridePendingTransition(R.anim.slide_up,R.anim.quite);
        edt_searching_book_str.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().isEmpty()){
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_empty);
                }else{
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_clean);
                }
            }
        });
    }



    @Override
    protected void init() {
        setTitleBarDividerGone();
        setTitleBarBg(R.color.white);
        setBackImg(R.mipmap.nav_btn_return_down);
        setTitleText("搜索");
//        setRightBtnText("微商城", R.color.lib_light_gray22);
        if (searchBookadapter == null) {

            searchBookadapter = new SearchBookAdapter(this, searchBookList, this, new SearchBookAdapter.OnAddClickListener() {
                @Override
                public void onAddClick(View view, EpaperInfo epaperInfo) {

                }
            });
        }
        lv_searchResult.setAdapter(searchBookadapter);
//        showSearchingView();
    }

    @Override
    protected void loadData() {
        hotWordAdapter = new HotWordAdapter(searchBookKeyNameBeanList);
        lv_hot_word.setAdapter(hotWordAdapter);
        loadHotWord();

    }

    private void loadHotWord() {
        SchoolDetail schoolDetail = EApplication.getInstance().getSchoolDetail();
        try{
            int schoolId = schoolDetail.getSchoolId();
            EpaperRequest.getBookKey(EApplication.BRAND_ID + "", schoolId + "", new BaseCallBack() {
                @Override
                public void success(Object data) {
                    searchBookKeyNameBeanList.clear();
                    super.success(data);
                    if (data != null) {
                        List<SearchBookKeyNameBean> searchBookKeyNameBean =  (List<SearchBookKeyNameBean>) data;
                        if(searchBookKeyNameBean.size()>0){
                            searchBookKeyNameBeanList .addAll (searchBookKeyNameBean);
                            showHotWordView();
                            hotWordAdapter.notifyDataSetChanged();
                        }
                    } else {
                        showNormalView();
                    }


                }

                @Override
                public void failed(int errorCode, Object data) {
                    showNormalView();
                }

                @Override
                public void failed(Object data) {
                    showNormalView();
                }
            });

        }catch (Exception e){

        }

    }



    /**
     * 添加书籍到书柜记录(上传到服务器)
     */
    public void setBookcaseToServer(final EpaperInfo clickEpaperInfo) {
        showCricleProgress();
        EpaperDao.getInstance().setBookcaseToServer(EApplication.BRAND_ID, clickEpaperInfo.getPackageId()
                , clickEpaperInfo.getServerId(), new BaseExtCallBack(SearchBookActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        hideCricleProgress();
                        DialogUtil.showFailedToastByErrorType(SearchBookActivity.this, data);

                    }

                    @Override
                    public void failed(Object data) {
                        super.failed(data);
                        hideCricleProgress();
                        DialogUtil.showFailedToastByErrorType(SearchBookActivity.this, data);

                    }

                    @Override
                    public void success(Object data) {
                        clickEpaperInfo.isBookCase = 1;
                        hideCricleProgress();
                        searchBookadapter.notifyDataSetChanged();
                        setResult(RESULT_OK);
                        toastInTop("1本书已添加到书桌");
                    }
                });
    }

    private int curPage = 1;


    /**
     *
     */
    private void loadDataFromNet() {
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            isSearching = false;
            return;
        }
        String putKeyWords = edt_searching_book_str.getText().toString();
        final String keyWords = putKeyWords.trim();
        if (TextUtils.isEmpty(keyWords)) {
//            CWToast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT, true).setToastType(CWToast.TOAST_TYPE_ERROR).show();
            isSearching = false;
            showNormalView();
            return;
        }
        String keyWord = putKeyWords;
        try {
            keyWord = URLEncoder.encode(keyWords, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        if (curPage == 1) {
            showSearchingView();
        }
        EpaperRequest.getSearchingBookListByKyeWord(
                EApplication.BRAND_ID+"",//品牌
                0+"",//年级
                0+"",//服务
                keyWord,//搜索关键字
                curPage,//curPage当前第几页
                LOAD_PAGE_SIZE,//每页数量

                new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        plv_searchbook.onHeaderRefreshComplete();
                        plv_searchbook.onFooterRefreshComplete();
                        isSearching = false;
                        showEmptyView();
                    }

                    @Override
                    public void failed(Object data) {
                        plv_searchbook.onHeaderRefreshComplete();
                        plv_searchbook.onFooterRefreshComplete();
                        isSearching = false;
                        showEmptyView();
                    }

                    @Override
                    public void success(Object data) {
                        isSearching = false;
                        plv_searchbook.onHeaderRefreshComplete();
                        plv_searchbook.onFooterRefreshComplete();
//                        BasePaging<EpaperInfo> epaperInfoBasePaging = (BasePaging<EpaperInfo>) data;
                        BookCaseBean bookCaseBean = (BookCaseBean) data;
                        List<EpaperInfo> epaperInfos = bookCaseBean.getProduct();
                        if (epaperInfos != null && epaperInfos.size() > 0) {
                            searchBookadapter.setKeyWords(keyWords);//设置搜索关键字高亮
                            reFreshUI(epaperInfos);
                        } else if (curPage == 1) {
                            showEmptyView();
                        } else {
                            showNormalView();
//                            plv_searchbook.getFooterTextView().setText("没有更多的搜索结果");
                        }

                        if(searchBookadapter.getCount()==bookCaseBean.pageCount){
                            plv_searchbook.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                        }else{
                            plv_searchbook.setFooterState(PullToRefreshView.PULL_TO_REFRESH);
                        }
                    }
                }
        );
    }

    private void reFreshUI(List<EpaperInfo> epaperInfos) {
        showNormalView();
        if (curPage == 1) {
            searchBookList.clear();
            searchBookList.addAll(epaperInfos);
        } else {
            searchBookList.addAll(epaperInfos);
        }
//        if (epaperInfos.size() < LOAD_PAGE_SIZE) { //获取到的数据比申请加载的数据要少,显示没有更多数据了
//            plv_searchbook.getFooterTextView().setText("没有更多的搜索结果");
//        } else {
//            plv_searchbook.getFooterTextView().setText("没有更多的搜索结果");
//        }
        searchBookadapter.notifyDataSetChanged();
        curPage++;
    }

    private CWDialog mErrorDialog = null;

    /**
     * 添加书籍失败
     */
    public void showErrorDialog() {
        mErrorDialog = new CWDialog(SearchBookActivity.this, false, false)
                .setMessage(getString(R.string.error_add_book), 16, Color.BLACK)
                .setPositiveButton("确定", null, true,
                        getResources().getDrawable(R.drawable.dialog_floor_selector));
        mErrorDialog.show();

    }


    /**
     * 监听键盘，如果是回车，就开始搜索书本
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            /*隐藏软键盘*/
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
            }
            if (!isSearching) {//防止监听键盘时搜索两次
                isSearching = true;
                curPage = 1;

                loadDataFromNet();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }



    /**
     * 是否正在搜索，
     * 防止监听键盘时搜索两次
     */
    private boolean isSearching = false;

    private void showSearchingView() {
        ll_hot_word.setVisibility(View.GONE);
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.VISIBLE);
//        Animation animation = AnimationUtils.loadAnimation(this, R.anim.loading_anim);
//        iv_searching_book.setAnimation(animation);
        //三个都隐藏,显示1个，显示第12个，显示123个
//        Animation animation = AnimationUtils.loadAnimation(this, R.anim.searching_anim);
//        iv_search_dot1.setAnimation(animation);
        startLoadingAnim( );


    }

    private void startLoadingAnim() {
        iv_search_dot1.setVisibility(View.GONE);
        iv_search_dot2.setVisibility(View.GONE);
        iv_search_dot3.setVisibility(View.GONE);
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
        loadingAnimHandler.sendEmptyMessageDelayed(1, 500);
        loadingAnimHandler.sendEmptyMessageDelayed(2, 1000);
        loadingAnimHandler.sendEmptyMessageDelayed(3, 1500);
        loadingAnimHandler.sendEmptyMessageDelayed(4, 2000);
    }

    private Handler loadingAnimHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    iv_search_dot1.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    iv_search_dot2.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    iv_search_dot3.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    startLoadingAnim();
                    break;
            }
        }
    };

    public void showHotWordView() {
        ll_hot_word.setVisibility(View.VISIBLE);
        lv_hot_word.setVisibility(View.VISIBLE);
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);
    }

    public void showNormalView() {
        ll_hot_word.setVisibility(View.GONE);
        plv_searchbook.setVisibility(View.VISIBLE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);
        removeAnimaMessages();
    }

    public void showEmptyView() {
        ll_hot_word.setVisibility(View.GONE);
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.VISIBLE);
        rel_searching.setVisibility(View.GONE);
        removeAnimaMessages();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAnimaMessages();
    }

    private void removeAnimaMessages() {
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        curPage = 1;
//        getServiceStateAndData();
        loadDataFromNet();
    }

    private static final int REQ_CODE_JUMP_TO_BOOK_DIRECTORY = 1;// 去书籍目录

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        loadDataFromNet();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int viewId = parent.getId();
        if (viewId == R.id.lv_searchbook) {//点击搜到的结果书本
            EpaperInfo epaperInfo = (EpaperInfo) searchBookadapter.getItem(position);
            if(epaperInfo!=null){
                EpaperJumpManager.jumpToCatalogFromSearching(
                        R.string.go_back,
                        this,
                        epaperInfo,
                        IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK,
                        REQ_CODE_JUMP_TO_BOOK_DIRECTORY,
                        epaperInfo == null ? -1 : epaperInfo.getServerId()
                );
            }

        } else if (viewId == R.id.lv_hot_word) {//点击热门搜索词
            String hotWord = searchBookKeyNameBeanList.get(position).keyName;
            edt_searching_book_str.setText(hotWord);
            loadDataFromNet();
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_CODE_JUMP_TO_BOOK_DIRECTORY && resultCode == Activity.RESULT_OK) { //添加书籍成功
            EpaperInfo epaperInfo = (EpaperInfo) data.getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
            for (int i = 0; i < searchBookList.size(); i++) {
                if (epaperInfo.productId.equals(searchBookList.get(i).productId) && epaperInfo.getPackageId().equals(searchBookList.get(i).getPackageId())) {
                    searchBookList.get(i).isBookCase = epaperInfo.isBookCase;
                    searchBookadapter.notifyDataSetChanged();
                    break;

                }
            }
            boolean isGoto_Desk = data.getBooleanExtra(CatalogNewActivity.CLOSE_ADDBOOKACTIVITY, false);
            if (isGoto_Desk) {//前往书桌
                Intent intent = new Intent();
                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ, epaperInfo);
                intent.putExtra(CatalogNewActivity.CLOSE_ADDBOOKACTIVITY, isGoto_Desk);
                setResult(RESULT_OK, intent);
                finish();
            }

        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_clear_keywords) {//清除搜索关键字
            edt_searching_book_str.setText("");
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_down,R.anim.quite);
    }
}
